package main

import (
	"fmt"
	"sync"
)

type singleton struct {
	value string
}

var once sync.Once
var instance *singleton

func GetInstance() *singleton {
	// 非并发情况下
	// if instance == nil {
	// 	instance = &singleton{value: "unique instance"}
	// }
	// 并发情况下，避免同时创建多个实例
	once.Do(func() {
		instance = &singleton{value: "unique instance"}
	})
	return instance
}

func main() {
	s1 := GetInstance()
	fmt.Println(s1.value) // unique instance

	s2 := GetInstance()

	if s1 == s2 {
		fmt.Println("s1 and s2 are the same instance")
	}

	// output
	// unique instance
	// s1 and s2 are the same instance
}
